package control;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import dao.UserDaoImpl;
import models.User;

public class LoginServlet extends HttpServlet {  //需要继承HttpServlet  并重写doGet  doPost方法
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);  //将信息使用doPost方法执行   对应jsp页面中的form表单中的method
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");

        String name = request.getParameter("userLoginName"); //得到jsp页面传过来的参数
        String pwd = request.getParameter("userLoginPasswd");
        System.out.println(name + "+" + pwd);
        User user = new User(); //实例化一个对象，将输入属性赋予该对象。
        user.setName(name);
        user.setPwd(pwd);

        UserDaoImpl ud = new UserDaoImpl();

        //根据登录名获取数据库中该用户除密码外的信息
        User sessionUser = null;

        //创建session
        HttpSession session = request.getSession();
        PrintWriter out = response.getWriter();
        String status = null;

        try {
            if (ud.checkUserInfo(user)) {        //检查用户名是否存在
                if (ud.checkPasswdInfo(user)){      //验证用户输入密码是否与数据库一致
                    System.out.println("login success ");       //存在则检验密码是否一致
                    //获取用户的用户名
                    sessionUser = ud.getUserAll(user);
                    //用户名user存入session
                    session.setAttribute("user", sessionUser);
                    //status为1 代表登录成功
                    session.setAttribute("status", "1");

                }else {
                    System.out.println("passwd don't same");
                    //status为2 代表密码不一致
                    session.setAttribute("status","2");
                }
            } else {
                System.out.println("please sign up");
                //status 为3 代表用户不存在，需要注册
                session.setAttribute("status", "3");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        status = (String) session.getAttribute("status");
        out.write(status);
        out.flush();
    }
}